import { MailerService } from '@nestjs-modules/mailer';
import {
  Body,
  Controller,
  Get,
  Post,
  UploadedFile,
  UseInterceptors,
} from '@nestjs/common';
import { FileInterceptor } from '@nestjs/platform-express';
import { ApiOkResponse, ApiOperation, ApiProperty } from '@nestjs/swagger';
import { AppService } from './app.service';

class email {
  @ApiProperty({ description: '用户名', example: '测试用户名' })
  email: string;
}

@Controller()
export class AppController {
  constructor(
    private readonly appService: AppService,
    private readonly mailerService: MailerService,
  ) {}

  @Post('upload')
  @ApiOkResponse({
    description: '成功',
  })
  @ApiOperation({ summary: '上传接口', description: '上传资源' })
  @UseInterceptors(FileInterceptor('file'))
  upload(@UploadedFile('file') file) {
    return file;
  }

  @Post('email')
  @ApiOkResponse({
    description: '成功',
  })
  @ApiOperation({ summary: '邮件接口', description: '发送邮件' })
  async email(@Body() body: email) {
    var aqq = /^[1-9][0-9]{4,10}@qq.com$/;
    const email = body.email;
    if (aqq.test(email)) {
      const randomNum = ('000000' + Math.floor(Math.random() * 999999)).slice(
        -6,
      );
      await this.mailerService.sendMail({
        to: email,
        from: '3111345436@qq.com',
        subject: 'CainBlog ✔',
        text: '验证码:' + randomNum,
      });

      return {
        code: 200,
        message: '验证成功,验证码已发送请确认',
        data: {
          to: email,
          email: randomNum,
        },
      };
    } else {
      return {
        code: 500,
        message: '邮箱格式不正确',
      };
    }
  }
}
